<template>
  <div class="knowledge-container">
    <!-- 头部工具栏 -->
    <div class="header-toolbar">
      <div class="left-section">
        <h2>知识管理</h2>
      </div>
      <div class="right-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索知识空间 (Ctrl+K)"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="showCreateSpaceDialog = true">
          <el-icon><Plus /></el-icon>
          新建空间
        </el-button>
        <el-button @click="navigateToSpaces">
          管理空间
        </el-button>
        <UserProfile />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div class="nav-section">
          <div class="nav-item" :class="{ active: activeTab === 'overview' }" @click="setActiveTab('overview')">
            <el-icon><House /></el-icon>
            <span>概览</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'spaces' }" @click="navigateToSpaces">
            <el-icon><Collection /></el-icon>
            <span>空间管理</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'recent' }" @click="setActiveTab('recent')">
            <el-icon><Clock /></el-icon>
            <span>最近访问</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'favorites' }" @click="setActiveTab('favorites')">
            <el-icon><Star /></el-icon>
            <span>我的收藏</span>
          </div>
        </div>


      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 概览视图 -->
        <div v-if="activeTab === 'overview'" class="overview-view">
          <div class="stats-cards">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><Collection /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalSpaces }}</div>
                <div class="stat-label">知识空间</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalPages }}</div>
                <div class="stat-label">文档页面</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><View /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalViews }}</div>
                <div class="stat-label">总阅读量</div>
              </div>
            </div>
          </div>

          <div class="recent-spaces">
            <h3>最近访问的空间</h3>
            <div class="spaces-grid">
              <div
                v-for="space in recentSpaces"
                :key="space.id"
                class="space-card"
                @click="enterSpace(space)"
              >
                <div class="space-icon" :style="{ backgroundColor: space.color || '#409EFF' }">
                  {{ space.name.charAt(0).toUpperCase() }}
                </div>
                <div class="space-info">
                  <h4>{{ space.name }}</h4>
                  <p class="space-desc">{{ space.description || '暂无描述' }}</p>
                  <div class="space-meta">
                    <span class="last-visit">{{ formatTime(space.lastVisit) }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="recentSpaces.length === 0" class="empty-state">
              <el-icon size="48"><Collection /></el-icon>
              <p>暂无最近访问的空间</p>
              <el-button type="primary" @click="navigateToSpaces">浏览所有空间</el-button>
            </div>
          </div>
        </div>

        <!-- 最近访问视图 -->
        <div v-if="activeTab === 'recent'" class="recent-view">
          <h3>最近访问</h3>
          <div class="recent-list">
            <div v-for="item in recentItems" :key="item.id" class="recent-item">
              <div class="item-icon">
                <el-icon v-if="item.type === 'space'"><Collection /></el-icon>
                <el-icon v-else><Document /></el-icon>
              </div>
              <div class="item-info">
                <h4>{{ item.name }}</h4>
                <p>{{ item.spaceName || item.description }}</p>
                <span class="visit-time">{{ formatTime(item.visitTime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 收藏视图 -->
        <div v-if="activeTab === 'favorites'" class="favorites-view">
          <h3>我的收藏</h3>
          <div class="favorites-list">
            <div v-for="item in favoriteItems" :key="item.id" class="favorite-item">
              <div class="item-icon">
                <el-icon v-if="item.type === 'space'"><Collection /></el-icon>
                <el-icon v-else><Document /></el-icon>
              </div>
              <div class="item-info">
                <h4>{{ item.name }}</h4>
                <p>{{ item.spaceName || item.description }}</p>
              </div>
              <div class="item-actions">
                <el-button size="small" @click="removeFavorite(item.id)">
                  <el-icon><StarFilled /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建空间对话框 -->
    <el-dialog v-model="showCreateSpaceDialog" title="新建空间" width="500px">
      <el-form :model="newSpace" label-width="80px">
        <el-form-item label="空间名称" required>
          <el-input v-model="newSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="标识">
          <el-input v-model="newSpace.identifier" placeholder="请输入空间标识" />
        </el-form-item>
        <el-form-item label="可见范围">
          <el-select v-model="newSpace.scopeType" placeholder="请选择可见范围">
            <el-option label="团队可见" value="user_group" />
            <el-option label="用户可见" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="可见性">
          <el-select v-model="newSpace.visibility" placeholder="请选择可见性">
            <el-option label="私有" value="private" />
            <el-option label="公开" value="public" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题色">
          <el-color-picker v-model="newSpace.color" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newSpace.description" type="textarea" placeholder="请输入空间描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="createSpace">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  House, Collection, Clock, Star, Plus, Setting, Document, View, StarFilled
} from '@element-plus/icons-vue'
import UserProfile from '@/components/knowledge/UserProfile.vue'
import request from '@/utils/request'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const activeTab = ref('overview')
const showCreateSpaceDialog = ref(false)

const spaces = ref([])
const recentItems = ref([])
const favoriteItems = ref([])

const newSpace = reactive({
  name: '',
  identifier: '',
  scopeType: 'user_group',
  visibility: 'private',
  color: '#409EFF',
  description: ''
})

// 计算属性
const totalSpaces = computed(() => spaces.value.length)
const totalPages = computed(() => {
  return spaces.value.reduce((total, space) => total + (space.pageCount || 0), 0)
})
const totalViews = computed(() => {
  return spaces.value.reduce((total, space) => total + (space.viewCount || 0), 0)
})
const recentSpaces = computed(() => {
  return spaces.value
    .filter(space => space.lastVisit)
    .sort((a, b) => (b.lastVisit || 0) - (a.lastVisit || 0))
    .slice(0, 6)
})

// 方法
const setActiveTab = (tab) => {
  activeTab.value = tab
}

const navigateToSpaces = () => {
  router.push('/knowledge/spaces')
}

const enterSpace = (space) => {
  router.push(`/knowledge/spaces/${space.id}`)
}

const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({
      path: '/knowledge/spaces',
      query: { search: searchQuery.value }
    })
  }
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 24 * 60 * 60 * 1000) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const loadSpaces = async () => {
  try {
    // 获取当前用户信息
    const currentUser = localStorage.getItem('currentUser') || ''
    
    const response = await request.get('/api/spaces/accessible', {
      params: {
        username: currentUser
      }
    })
    if (response.data.code === '200') {
      spaces.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载空间失败:', error)
  }
}

const loadRecentItems = async () => {
  // 模拟数据，实际应该从API获取
  recentItems.value = [
    {
      id: 1,
      name: '项目文档',
      type: 'page',
      spaceName: '开发团队',
      visitTime: Date.now() - 2 * 60 * 60 * 1000
    },
    {
      id: 2,
      name: '开发团队',
      type: 'space',
      description: '团队协作空间',
      visitTime: Date.now() - 5 * 60 * 60 * 1000
    }
  ]
}

const loadFavoriteItems = async () => {
  // 模拟数据，实际应该从API获取
  favoriteItems.value = [
    {
      id: 1,
      name: 'API文档',
      type: 'page',
      spaceName: '技术文档'
    }
  ]
}

const removeFavorite = async (itemId) => {
  favoriteItems.value = favoriteItems.value.filter(item => item.id !== itemId)
  ElMessage.success('已取消收藏')
}

const createSpace = async () => {
  if (!newSpace.name) {
    ElMessage.warning('请输入空间名称')
    return
  }
  
  try {
    // 获取当前用户信息
    const currentUser = localStorage.getItem('currentUser') || ''
    
    const spaceData = {
      ...newSpace,
      createdBy: {
        id: '1',
        username: currentUser
      },
      updatedBy: {
        id: '1',
        username: currentUser
      }
    }
    
    const response = await request.post('/api/spaces', spaceData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.code === '200') {
      ElMessage.success('创建成功')
      showCreateSpaceDialog.value = false
      Object.assign(newSpace, {
        name: '',
        identifier: '',
        scopeType: 'user_group',
        visibility: 'private',
        color: '#409EFF',
        description: ''
      })
      loadSpaces()
      // 创建成功后跳转到空间管理页面
      router.push('/knowledge/spaces')
    } else {
      ElMessage.error(response.data.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建空间失败:', error)
    ElMessage.error('创建空间失败')
  }
}

// 生命周期
onMounted(() => {
  loadSpaces()
  loadRecentItems()
  loadFavoriteItems()
})
</script>

<style scoped>
.knowledge-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.left-section h2 {
  margin: 0;
  color: #333;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 240px;
  background: white;
  border-right: 1px solid #e8e8e8;
  padding: 16px 0;
  overflow-y: auto;
}

.nav-section {
  margin-bottom: 24px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  color: #666;
}

.nav-item:hover {
  background-color: #f5f5f5;
  color: #333;
}

.nav-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-right: 3px solid #1890ff;
}

.nav-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}



.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #e6f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: #1890ff;
  font-size: 24px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.recent-spaces {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.recent-spaces h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.spaces-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.space-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e8e8e8;
}

.space-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.space-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 12px;
}

.space-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.space-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.space-meta {
  font-size: 12px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state .el-icon {
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 16px 0;
}

.recent-view,
.favorites-view {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.recent-view h3,
.favorites-view h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.recent-list,
.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recent-item,
.favorite-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.recent-item:hover,
.favorite-item:hover {
  background: #e9ecef;
}

.item-icon {
  margin-right: 12px;
  color: #666;
  font-size: 20px;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 14px;
}

.item-info p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.visit-time {
  font-size: 12px;
  color: #999;
}

.item-actions {
  margin-left: 12px;
}
</style>